package com.avic.rong;


import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.avic.rong.activity.MiddleActivity;
import com.avic.rong.bean.DaoMaster;
import com.avic.rong.bean.DaoSession;
import com.avic.rong.bean.LoginBean;
import com.avic.rong.search.db.MyDataBaseHelper;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DeviceUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.Utils;
import com.example.minato.minastore.RxRetrofitApplication;
import com.example.minato.minastore.utils.AppUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.microquation.linkedme.android.LinkedME;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.socialize.PlatformConfig;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import wendu.dsbridge.DWebView;


/**
 * Creater: Created by wangyz on 2018/12/11.
 * Email: 936804097@qq.com
 */
public class MyApplication extends Application {


//    private DaoMaster.DevOpenHelper mHelper;
//    private SQLiteDatabase db;
//    private DaoMaster mDaoMaster;
//    private DaoSession mDaoSession;
    private static MyApplication instance;
    public LoginBean userLoginBean;
    public Integer orderId;//当前支付订单Id
    private DaoSession daoSession;

    //微信
    public static final String AppID = "wx1a2342346402f5b2";
    public static final String AppSecret = "47f9b3c39ca9b12c237c269e8ec19999";

    //QQ
    public static final String QQAppID = "1109640435";
    public static final String QQAppSecret = "KEYR17kxdZd65dLcSfK";

    // 新浪微博
    public static String SINA_APP_KEY = "317455678";
    public static String SINA_APP_SECRET = "2bfb84dda1473f60201d54982854bd82";
    public static String SINA_CALLBACK_URL = "https://sns.whalecloud.com/sina2/callback";//新浪回调地址修改


    private List<Activity> oList = new ArrayList<Activity>();//用于存放所有启动的Activity的集合

    @Override
    public void onCreate() {
        super.onCreate();

        MyApplication.instance = this;
        RxRetrofitApplication.init(this);
        RxRetrofitApplication.setDebug(true);

        Utils.init(this);
        initGreenDao();
        // getDbHelper();
        //5d26f8b43fc1950ccc000619

        //侧滑
        BGASwipeBackHelper.init(this, null);
        DWebView.setWebContentsDebuggingEnabled(true);

        //5.日志初始化
        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });


        //初始化用户
        initUserInfo();

        Logger.addLogAdapter(new AndroidLogAdapter(){
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return true;
            }
        });

        //友盟初始化
//        UMConfigure.init(this,"5d26f8b43fc1950ccc000619","umeng",UMConfigure.DEVICE_TYPE_PHONE,"");//58edcfeb310c93091c000be2 5965ee00734be40b580001a0
//        UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE,"");//58edcfeb310c93091c000be2 5965ee00734be40b580001a0

        //初始化组件化基础库, 统计SDK/推送SDK/分享SDK都必须调用此初始化接口
        UMConfigure.init(this, PlatfromContants.UMENG_APPKEY, "umeng", UMConfigure.DEVICE_TYPE_PHONE,"");
        //友盟集成测试
        UMConfigure.setLogEnabled(false);
        // interval 单位为毫秒，如果想设定为40秒，interval应为 40*1000.
        MobclickAgent.setSessionContinueMillis(30 * 1000);

        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        // 支持在子进程中统计自定义事件
        UMConfigure.setProcessEvent(true);


        PlatformConfig.setWeixin(AppID, AppSecret);
        PlatformConfig.setQQZone(QQAppID, QQAppSecret);
        PlatformConfig.setSinaWeibo(SINA_APP_KEY, SINA_APP_SECRET,SINA_CALLBACK_URL);


        String[] test =  DeviceUtils.getTestDeviceInfo(this);

        //获取设备ID
        String imeString = DeviceUtils.getIMEString(instance);
        Logger.e("wcx", "onCreate: "+imeString );
        SharedPreferencesUtil.getInstance().setIME_ID(imeString);


        //link Me
        LinkedME.getInstance(this, "5de2e81cbd84bd178ec8c1c69a6569fe");

//        if (BuildConfig.DEBUG) { //设置debug模式下打印LinkedME日志
//            LinkedME.getInstance().setDebug();


        //初始时请设置为false
        LinkedME.getInstance().setImmediate(false);
        //设置处理跳转逻辑的中转页，MiddleActivity详见后续配置
        LinkedME.getInstance().setHandleActivity(MiddleActivity.class.getName());


        //友盟推送
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                //Log.i(TAG,"注册成功：deviceToken：-------->  " + deviceToken);
            }
            @Override
            public void onFailure(String s, String s1) {
               // Log.e(TAG,"注册失败：-------->  " + "s:" + s + ",s1:" + s1);
            }
        });

    }

  /*  private UMSocialService mController = UMServiceFactory
            .getUMSocialService("com.umeng.login");

    private void addWXPlatform() {
        // 注意：在微信授权的时候，必须传递appSecret
        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
        String appId = "wx.....";
        String appSecret = "gdfg......";
        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(LoginActivity.this, appId,
                appSecret);

        wxHandler.setRefreshTokenAvailable(true);

        wxHandler.addToSocialSDK();

    }*/

    public SQLiteDatabase getDbHelper() {
        MyDataBaseHelper helper = new MyDataBaseHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        return db;
    }


    public static MyApplication getInstance(){
        return instance;
    }


    private void initUserInfo() {
        String userInfo = SharedPreferencesUtil.getInstance(this).getAsString(ConstantsUtils.USER_INFO, "");
        if (!TextUtils.isEmpty(userInfo)) {
            Gson gson = new Gson();
            Type type = new TypeToken<LoginBean>() {
            }.getType();
            userLoginBean = gson.fromJson(userInfo, type);
        }
    }

    private void initGreenDao() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, AppUtils.DB_NAME);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();

//        com.example.minato.minastore.cookie.DaoMaster.DevOpenHelper helperTwo = new com.example.minato.minastore.cookie.DaoMaster.DevOpenHelper(this, AppUtils.DB_NAME);
//        SQLiteDatabase dbTwo = helperTwo.getWritableDatabase();
//        com.example.minato.minastore.cookie.DaoMaster daoMasterTwo = new com.example.minato.minastore.cookie.DaoMaster(dbTwo);
//        com.example.minato.minastore.cookie.DaoSession daoSession = daoMasterTwo.newSession();

    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.color_fff4f4f4, R.color.color_c2c2c2);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    /**
     * 添加Activity
     */
    public void addActivity_(Activity activity) {
// 判断当前集合中不存在该Activity
        if (!oList.contains(activity)) {
            oList.add(activity);//把当前Activity添加到集合中
        }
    }

    /**
     * 销毁单个Activity
     */
    public void removeActivity_(Activity activity) {
//判断当前集合中存在该Activity
        if (oList.contains(activity)) {
            oList.remove(activity);//从集合中移除
            activity.finish();//销毁当前Activity
        }
    }

    /**
     * 销毁所有的Activity
     */
    public void removeALLActivity_() {
        //通过循环，把集合中的所有Activity销毁
        for (Activity activity : oList) {
            activity.finish();
        }
    }

}
